# -*- coding: utf-8 -*-
import uuid
from datetime import datetime

from django import forms
from django.contrib.auth.models import User

from .models import CustomUser



class ProfileForm(forms.ModelForm):

    class Meta:
        model = CustomUser
        exclude = ('user', 'gallery',)

class RegistrationProfileForm(forms.ModelForm):
	username = forms.RegexField(label=u'Имя пользователя', max_length=30,
		regex=r'^[\w.-]+$', error_messages={'invalid': 
			'This value may contain only letters, numbers and ./-/_ characters.'})
	password = forms.CharField(label=u'Пароль',
        widget=forms.PasswordInput(render_value=False))
	password_repeat = forms.CharField(label=u'Пароль еще раз',
        widget=forms.PasswordInput(render_value=False))
	first_name = forms.CharField(label=u'Ваше имя', max_length=30)
	last_name = forms.CharField(label=u'Ваша фамилия', max_length=30)

	class Meta:
		model = CustomUser
		fields = ('email', 'first_name', 'last_name',
			 	'password', 'password_repeat')

	def __init__(self, *args, **kwargs):
		super(RegistrationProfileForm, self).__init__(*args, **kwargs)
		self.fields['username'].widget = forms.widgets.HiddenInput()
		self.fields['username'].required = False

	def _generate_username(self):
		""" Generate a unique username """
		while True:
		    # Generate a UUID username, removing dashes and the last 2 chars
		    # to make it fit into the 30 char User.username field. Gracefully
		    # handle any unlikely, but possible duplicate usernames.
		    username = str(uuid.uuid4())
		    username = username.replace('-', '')
		    username = username[:-2]

		    try:
		        User.objects.get(username=username)
		    except User.DoesNotExist:
		        return username

	def clean_username(self):
		return self._generate_username()

	def clean_email(self):
		# email must be uniq
		new_email = self.cleaned_data['email']

		emails = User.objects.filter(email__iexact=new_email).count()

		from userprofiles.contrib.emailverification.models import EmailVerification

		emails += EmailVerification.objects.filter(
		    new_email__iexact=new_email, is_expired=False).count()

		if emails > 0:
		    raise forms.ValidationError(u'Этот адрес уже сипользуется! Укажите другой.')

		return new_email

	def clean(self):
		if 'password' in self.cleaned_data and 'password_repeat' in self.cleaned_data:
			if self.cleaned_data['password'] != self.cleaned_data['password_repeat']:
				raise forms.ValidationError(u'Введеные пароли ене совпадают! Попробуйте еще раз.')
		if not('first_name' in self.cleaned_data and 'last_name' in self.cleaned_data):
			raise forms.ValidationError(u'Не указаны имя или фамилия!')
		return self.cleaned_data

	'''def save_profile(self, new_user, *args, **kwargs):
		self.__meta.objects.save()'''

	def save(self, *args, **kwargs):
		from userprofiles.contrib.accountverification.models import AccountVerification

		new_user = AccountVerification.objects.create_inactive_user(
		    username=self.cleaned_data['username'],
		    password=self.cleaned_data['password'],
		    email=self.cleaned_data['email'],
		)
		new_user.save()

		if hasattr(self, 'save_profile'):
			self.save_profile(new_user, *args, **kwargs)

		return new_user